<template>
    <div class="many-tree-wrap" v-clickoutside="closeTreeFun">
        <section class='search_cont'>
            <el-input @focus="inputFocus" v-model="groupName" :disabled="inputDisabled" readonly :placeholder="placeholder"></el-input>
            <i class="fa fa-times close-manytree" 
                @click="clearTreePop" title="清空" v-show='!inputDisabled'>
            </i>
        </section>
        <section v-show='showTree' class='manytree'>
            <el-input class="search-inpt" placeholder="选择组" v-model="filterText"></el-input>
            <div class="content-inner">
                <el-tree 
                    v-if="multiple" 
                    v-loading="loading"
                    :data="treeData" 
                    class="rescmtree" 
                    node-key="id"
                    :props="defaultProps"
                    :check-strictly="true" 
                    show-checkbox
                    default-expand-all
                    :check-on-click-node="true"
                    :filter-node-method="filterNode" 
                    highlight-current
                    ref="tree" 
                    @check="treeCheck">
                </el-tree>
                <el-tree 
                    v-if="!multiple" 
                    v-loading="loading"
                    :data="treeData"
                    class="rescmtree" 
                    node-key="id"
                    :props="defaultProps"
                    :filter-node-method="filterNode" 
                    highlight-current
                    ref="tree2" 
                    @node-click="nodeClick">
                </el-tree>
            </div>
        </section>
    </div>
</template>
<script>
import { initDeptTree } from "@/service/core/deptConf";
import { isArray, transformTozTreeFormat } from "@/utils/Tools";
import { mapState } from 'vuex'
export default {
    name: 'selectDept', // 机构选择下拉框
    props: {
        multiple: { // 是否多选
            type: Boolean,
            default: false
        },
        value: { // v-model绑定值
            type: [String, Array],
            default() {
                if(this.multiple) {
                    return []
                }else {
                    return ''
                }
            }
        },
        label: { // 机构名称
            type: [String, Array],
            default() {
                if(this.multiple) {
                    return []
                }else {
                    return ''
                }
            }
        },
        disabled:{ // 是否禁用
            type: Boolean,
            default:false,
        },
        placeholder: String,
        max: {
            type: Number,
            default: 0
        },
        statusId: {
            type: String,
            default: 'ACTIVE'
        },
        tenemId: { // 租户id 若需更改则传入
            type: String,
            default: ''
        }
    },
    inject: ['elForm'],
    data() {
        return {
            showTree: false,
            filterText: '',
            treeData: [],
            defaultProps: {
                children: "children",
                label: "name",
                value: 'id'
            },
            loading: false,
        };
    },
    watch: {
        value(val) {
            if(!this.multiple) {
                if(!val) {
                    this.groupName = '';
                }
            }else {
                if(val.length == 0) {
                    this.groupName = [];
                }
            }
        },
        filterText(val) {
            if(this.$refs.tree && this.multiple) {
                this.$refs.tree.filter(val);
            }
            if(this.$refs.tree2 && !this.multiple) {
                this.$refs.tree2.filter(val);
            }
		},
    },
    computed: {
        groupName: {
            get: function() {
                if(!this.multiple) {
                    return this.label;
                }else {
                    return this.label.join();
                }
                
            },
            set: function(val) {
                this.$emit("update:label", val);
            } 
        },
        inputDisabled() {
            return this.disabled || (this.elForm || {}).disabled;
        },
        ...mapState({
            tenementId: state => state.token.tenementId
        })
    },
    methods: {
        inputFocus() {
            this.showTree = true;
            if(!this.treeData.length) {
                this.deptTreeInit();
            }else {
                this.$nextTick(() => {
                    if(this.multiple) {
                        this.$refs.tree.setCheckedKeys(this.value, false);
                    }else {
                        this.$refs.tree2.setCurrentKey(this.value);
                    }
                })
            }
        },
        filterNode(value, data) { 
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
        },
        nodeClick(treeNode) {
            this.$emit("input", treeNode.id);
            this.groupName = treeNode.name;
            this.$emit('change', treeNode.id, treeNode);
            this.closeTreeFun();
        },
        treeCheck(node, obj) {
            let checkedNodes = obj.checkedNodes;
            let ids = checkedNodes.map(v => v.id);
            let labels = checkedNodes.map(v => v.name);
            if(this.max > 0) {
                if(ids.length > this.max) {
                    this.$message(`最多可选择${this.max}个！`, {type: 'warning'});
                    this.$refs.tree.setCheckedKeys(this.value, false);
                    return
                }
            }
            this.$emit('input', ids);
            this.groupName = labels;
        },
        deptTreeInit() {
            let params = { 
                statusId: "ACTIVE" , 
                columns: 'path,orderNum', 
                orders: 'true,true',
                statusId: this.statusId,
                tenementId: this.tenemId || this.tenementId
            };
            this.loading = true;
            initDeptTree(params).then(res => {
                if (res.data.code == 1000 && isArray(res.data.data)) {
                    var data = res.data.data;
                    // data = data.filter(v => v.statusId == "ACTIVE");
                    data = transformTozTreeFormat(data);
                    this.treeData = [...data];
                    this.$nextTick(() => {
                        if(this.multiple) {
                            this.$refs.tree.setCheckedKeys(this.value, false);
                        }else {
                            this.$refs.tree2.setCurrentKey(this.value);
                        }
                    })
                }
                this.loading = false;
            }).catch(error => {
                this.loading = false;
            })
        },
        clearTreePop() {
            if(this.multiple) {
                this.$emit('input', []);
                this.groupName = [];
            }else {
                this.$emit('input', '');
                this.groupName = '';
            }
        },
        closeTreeFun() { // 点击空白处关闭
            this.showTree = false;
            this.filterText = null;
        },
    }
};
</script>
<style lang="scss" scoped>
.manytree .el-icon-close {
    position: absolute;
    right: -20px;
    top: 7px;
    cursor: pointer;
}
.manytree {
    z-index: 1990;
    position: absolute;
    border: 1px solid #ddd;
    height: 250px;
    min-width: 200px;
    width: 100%;
    padding: 3px;
    background: #fff;
    .content-inner{
        height: 200px;
        margin-top: 5px;
        overflow: auto;
    }
}
.many-tree-wrap {
    position: relative;
}
.close-manytree {
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 14px;
    cursor: pointer;
}

.search-inpt /deep/ {
    input {
        border: 1px solid #DCDFE6 !important;
    }
}
</style>
